package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.db.api.PeachBlossomAudioApi;
import com.tanhua.dubbo.db.api.PeachBlossomUserApi;
import com.tanhua.dubbo.db.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.PeachBlossomAudio;
import com.tanhua.model.mongo.PeachBlossomUser;
import com.tanhua.model.vo.PeachBlossomVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

//桃花传音 service层
@Service
public class PeachblossomService {

    @Autowired
    private FastFileStorageClient client; //从调度服务器获取，一个目标存储服务器，上传到FastDFS文件系统中

    @Autowired
    private FdfsWebServer webServer; //获取存储服务器的请求URL

    @DubboReference
    private PeachBlossomAudioApi audioApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private PeachBlossomUserApi peachBlossomUserApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //保存桃花传音
    public void savePeachblossom(MultipartFile soundFile) throws IOException {

        //0.解析传过来的语音文件 soundFile

        //获取上传的文件名
        String filename = soundFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1); //根据.的索引加1截取前部分

        //1.上传语音到FastDFS文件系统中 //文件输出流，长度，文件名，源数据
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), filename, null);

        //2.获取语音path路径(拼接访问路径)
        String audioUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        //3.构建PeachBlossomAudio对象
        Long userId = UserHolder.getUserId();

        PeachBlossomAudio audio = new PeachBlossomAudio();
        audio.setAudioUrl(audioUrl);
        audio.setUserId(userId);
        audio.setCreated(System.currentTimeMillis());

        //4.调用Api保存到MongoDB中
        audioApi.savePeachBlossomAudio(audio);

    }


    //桃花传音-接收语音（学生实战）
    public PeachBlossomVo findPeachblossom() {

        //获取登录着id
        Long toUserId = UserHolder.getUserId();

        //获取当日时间
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        //1.查询语音数据之前 先检查该用户今日是否还有次数获取语音
        PeachBlossomUser peachBlossomUser = peachBlossomUserApi.findByUserIdAndDate(toUserId, today);

        //  查询数据存在，且获取次数小于等于0，返回空数据
        if (peachBlossomUser != null && peachBlossomUser.getRemainingTimes() <= 0) {

            return new PeachBlossomVo();

        }

        //2. 调用Api随机获取一条语音数据
        PeachBlossomAudio audio = audioApi.findPeachblossom(toUserId);

        //3. 更新PeachBlossomAudio表中语音数据对应的tag数据
        int tag=1;
        audioApi.updatePeachblossom(audio,tag);


        //如果数据库没有数据？？？？ 怎么构建返回值
        if (audio == null) {
            return new PeachBlossomVo();
        }

        //4.构造返回值：

        //4.1 根据audio中的userId获取该语音的用户信息
        UserInfo userInfo = userInfoApi.findById(audio.getUserId());

        //4.2 创建返回值对象
        PeachBlossomVo vo = PeachBlossomVo.init(userInfo, audio);

        //构建PeachBlossomUser,保存获取语音的用户信息
        //String key="Audio"+"_"+"User";
        //String valueKey=toUserId.toString()+"_"+today;

        //String value=vo.getRemainingTimes().toString();

        //redisTemplate.opsForHash().put();


        //将数据存入数据库中：
        if (peachBlossomUser == null) {
            //如果没有数据 ，保存
            peachBlossomUser = new PeachBlossomUser();
            peachBlossomUser.setCreated(System.currentTimeMillis());
            peachBlossomUser.setUserId(toUserId);
            peachBlossomUser.setDate(today);
            peachBlossomUser.setRemainingTimes(9);
            peachBlossomUserApi.savePeachBlossomUser(peachBlossomUser);
        } else {
            //有数据 ，更新
            int strCount = peachBlossomUser.getRemainingTimes().intValue() - 1;
            Integer count = Integer.valueOf(strCount);
            peachBlossomUserApi.update(peachBlossomUser,count);
            //重新赋值
            vo.setRemainingTimes(count);

        }

        //构建返回
        return vo;

    }
}